<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 小麦13
 */
class Xiaomai13Controller extends PayController{
    protected $config;
    protected $class;
    protected $public_key;
    protected $private_key;
    protected $key_len;
    private $pay_url;
    private $mch_id;
    private $query_url;
    const RSA_ALGORITHM_KEY_TYPE = OPENSSL_KEYTYPE_RSA;
    const RSA_ALGORITHM_SIGN = OPENSSL_ALGO_SHA256;

    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));

        $this->private_key = file_get_contents("Files/Xiaomai/private.txt");
        $this->public_key = file_get_contents("Files/Xiaomai/web_public.txt");

        $pub_id = openssl_get_publickey($this->public_key);
        $this->key_len = openssl_pkey_get_details($pub_id)['bits'];
        $this->query_url = 'http://int.megaxpay.com/pay/query_order';
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $product = Product::getInstance()->getById(I("request.pay_bankcode",0,"intval"));
        if(!$product){
            $this->showmessage('未找到支付产品!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        $return = $this->orderadd($parameter);


        $this->pay_url = 'http://int.megaxpay.com/pay/add_order';
        $this->mch_id = $this->config['mch_id'];

        $data = [];
        $data['merchNo'] = $this->config['mch_id'];
        $data['orderNo'] = $return['orderid'];
        $data['amount'] = intval($return['amount']*100);
        $data['currency'] = 'CNY';
        $data['payType'] = 1;
        switch($this->config['paytype']){
            case 1:
                $data['payType'] = 13;
                break;
            default:
                $this->showmessage('此通道暂不支持此支付方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }
        $data['title'] = 'xm';
        $data['desc'] = 'x';
        $data['returnUrl'] = $return['callbackurl'];
        $data['notifyUrl'] = $return['notifyurl'];
        $data['reqTime'] = date("YmdHis",time());
        $data['reqIp'] = getIP();
        $data['userId'] = 'aaa';

        $context = $this->publicEncrypt(json_encode($data));
        $sign = $this->sign($context);

        $postArr = [
            'context' => $context,
            'sign' => $sign,
            'encryptType' => 'RSA',
        ];

        $resPay = $this->curlPost($this->pay_url, json_encode($postArr));
        $res = json_decode($resPay, true);

        if ($res['code'] != '0') {
            if($res['msg']){
                $this->showmessage($res['msg'],['code'=>C("THIRDCODES.".$this->class)]);
            }
            $this->showmessage('获取支付链接失败!',['code'=>C("THIRDCODES.".$this->class)]);
        }


        $res_context = json_decode($this->privateDecrypt($res['context']), true);

        $code = $res_context['redirectUrl'];

        if(!$code){
            $this->showmessage("支付链接错误",['code'=>C("THIRDCODES.".$this->class)]);
        }

        header("Location:{$code}");
    }

    public function notifyurl(){
        $this->debug_callback();
        if(!$this->checkip(getIP(),['150.109.113.241'])){
            //exit("wrong");
        }

        $p = file_get_contents("php://input");
        //$p = '{"context":"WSYEAnTL3ECAuA9kUuhNCSrkmH9TtZVGTeWsMD/l5q4y6HOo14Z+R7+sVs9JY4hpMjR7hKdeEE1W59c6iLjyLhDU4bxgR9iBY6X6WjZPhYVegu4gI0Qz0wqnWoBgG81yA5xsJIQITTqHN1ghgSQPW+gnyy17TI9TdL10we30/7swbF4pnEW8sfLeFd2Lh6AGwk4VnV9kEDdwJ14G25sFM3bCdkVMgm2xZXLmrhICFj3Wh46OliXC69EmHD65PRvziqWPBFnPvNuQH62Y6HBL7FenwO6RQbs+U6Efmr/KG9llirTr/qQionITb8IKVhKnRJfXcOE4D8FvkT0IDzaITA==","encryptType":"RSA","sign":"DJxnCzQ1uSZGR1mtv2JKT0AY460aJ6Q1bVRHE/2EB/tXmhY8AOvGrdSvrifT1xz0JUvACA07dKZvxe7z+vsDhUcBV5IQx5SJR0IH6jCKaHD9iYQ+7doV8DPLO6RV5KB/3qYqOhVrrsA9qzb8hrIMyLc5rMwbmF70BaI4K6NawkYfClBFtD/xPCkKSf3xj5n//rxB5o49Z+T6WKSXXomOo0hUdyGSgtxMMb28cR4d17Dv29gUWbak2kPvG1nRROgcQVzC3rcJusvXl9pPHZdWQxwRKG1nrMjItjTUZKsmQD6Vs/aJAr+cdm7H3DiW/uWy6KQ9j+nCe7g26JklVNgOgQ=="}';

        $p = json_decode($p, true);

        if(empty($p)){
            exit("wrong");
        }

        $p = json_decode($this->privateDecrypt($p['context']), true);

        if ($p['orderState'] !== 0) {
            exit("pay fail");
        }

        /*
         * Array
        (
            [amount] => 101
            [businessNo] => 20190416191257c6a21ec2
            [merchNo] => YPSH94587340
            [orderNo] => 2019041619125725352
            [orderState] => 0
        )
         */

        //获取订单信息
        $orderid = $p['orderNo'];
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            exit("order not found");
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(

            "pay_orderid_rd"=>htmlspecialchars($p['businessNo'])
        ));

        //处理支付
        $this->async($find['pay_orderid'],'ok');
    }





    public static function createKeys($key_size = 2048) {
        $config = array(
            "private_key_bits" => $key_size,
            "private_key_type" => self::RSA_ALGORITHM_KEY_TYPE,
        );
        $res = openssl_pkey_new($config);
        openssl_pkey_export($res, $private_key);
        $public_key_detail = openssl_pkey_get_details($res);
        $public_key = $public_key_detail["key"];
        return [
            "public_key" => $public_key,
            "private_key" => $private_key,
        ];
    }

    public function publicEncrypt($data) {
        $encrypted = '';
        $part_len = $this->key_len / 8 - 11;
        $parts = str_split($data, $part_len);
        $res = openssl_pkey_get_public($this->public_key);

        foreach ($parts as $part) {
            $encrypted_temp = '';
            openssl_public_encrypt($part, $encrypted_temp, $res);
            $encrypted .= $encrypted_temp;
        }
//        formatPut($encrypted);
        return base64_encode($encrypted);
//        return $this->url_safe_base64_encode($encrypted);
    }

    public function privateDecrypt($encrypted) {
        $decrypted = "";
        $part_len = $this->key_len / 8;
        $base64_decoded = $this->url_safe_base64_decode($encrypted);
        $parts = str_split($base64_decoded, $part_len);
        foreach ($parts as $part) {
            $decrypted_temp = '';
            openssl_private_decrypt($part, $decrypted_temp, $this->private_key);
            $decrypted .= $decrypted_temp;
        }
        return $decrypted;
    }

    public function privateEncrypt($data) {
        $encrypted = '';
        $part_len = $this->key_len / 8 - 11;
        $parts = str_split($data, $part_len);
        foreach ($parts as $part) {
            $encrypted_temp = '';
            openssl_private_encrypt($part, $encrypted_temp, $this->private_key);
            $encrypted .= $encrypted_temp;
        }
        return url_safe_base64_encode($encrypted);
    }

    public function publicDecrypt($encrypted) {
        $decrypted = "";
        $part_len = $this->key_len / 8;
        $base64_decoded = $this->url_safe_base64_decode($encrypted);
        $parts = str_split($base64_decoded, $part_len);
        foreach ($parts as $part) {
            $decrypted_temp = '';
            openssl_public_decrypt($part, $decrypted_temp, $this->public_key);
            $decrypted .= $decrypted_temp;
        }
        return $decrypted;
    }

    public function sign($data) {
        $res = openssl_pkey_get_private($this->private_key);
        openssl_sign($data, $sign, $res, OPENSSL_ALGO_SHA256);
        return base64_encode($sign);
    }

    public function verify1($data, $sign) {
        $pub_id = openssl_get_publickey($this->public_key);
        $res = openssl_verify($data, $this->url_safe_base64_decode($sign), $pub_id, OPENSSL_ALGO_SHA256);
        return $res;
    }

    function url_safe_base64_decode($data) {
        $base_64 = str_replace(array('-', '_'), array('+', '/'), $data);
        return base64_decode($base_64);
    }

    function url_safe_base64_encode($data) {
        return str_replace(array('+', '/', '='), array('-', '_', ''), base64_encode($data));
    }

    function base64_to_url_safe_base64($data) {
        return str_replace(array('+', '/', '='), array('-', '_', ''), $data);
    }

    function url_safe_base64_to_base64($data) {
        return str_replace(array('-', '_'), array('+', '/'), $data);
    }

    function curlPost($url, $data = '') {
        $headers = [
            "Content-type: application/json;charset='utf-8'",
            "Accept: application/json",
            "Cache-Control: no-cache",
            "Pragma: no-cache",
        ];
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_TIMEOUT, 60);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSLVERSION, 1);//这个值不设置有时会出现error 35情况
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        return curl_exec($ch);
    }
}